<template>
  <div class="app-container">
    <!-- 地址列表 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="address in addressList" :key="address.id">
        <el-card class="address-card" :class="{ 'is-default': address.isDefault === 1 }">
          <div class="address-info">
            <h3>{{ address.name }} {{ address.phone }}</h3>
            <p>{{ address.province }}{{ address.city }}{{ address.district }}</p>
            <p>{{ address.detailAddress }}</p>
            <el-tag v-if="address.isDefault === 1" size="small" type="success">默认地址</el-tag>
          </div>
          <div class="address-actions">
            <el-button type="text" @click="handleSetDefault(address)" v-if="address.isDefault === 0">设为默认</el-button>
            <el-button type="text" @click="handleEdit(address)">编辑</el-button>
            <el-button type="text" @click="handleDelete(address)">删除</el-button>
          </div>
        </el-card>
      </el-col>
      <!-- 添加新地址卡片 -->
      <el-col :span="6">
        <el-card class="address-card add-card" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <p>添加新地址</p>
        </el-card>
      </el-col>
    </el-row>

    <!-- 地址编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="addressRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所在地区" prop="provinceId">
          <el-cascader
            v-model="regionIds"
            :options="regionOptions"
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input 
            v-model="form.detailAddress" 
            type="textarea" 
            placeholder="请输入详细地址" 
          />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { 
  listAddress, 
  getAddress, 
  addAddress, 
  updateAddress, 
  delAddress,
  setDefaultAddress 
} from '@/api/member/address'
import { ElMessage, ElMessageBox } from 'element-plus'
import { regionData } from '@/utils/region-data'

const addressList = ref([])
const open = ref(false)
const title = ref('')
const regionIds = ref([])
const regionOptions = ref(regionData)

const form = ref({
  id: undefined,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  provinceId: undefined,
  cityId: undefined,
  districtId: undefined,
  detailAddress: '',
  isDefault: 0
})

const rules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  provinceId: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

const addressRef = ref(null)

// 获取地址列表
const getList = async () => {
  try {
    const res = await listAddress()
    addressList.value = res.rows
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 处理添加地址
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加地址'
}

// 处理编辑地址
const handleEdit = async (address) => {
  reset()
  const id = address.id
  try {
    const response = await getAddress(id)
    form.value = response.data
    // 设置地区选择器的值
    regionIds.value = [form.value.provinceId, form.value.cityId, form.value.districtId].filter(Boolean)
    open.value = true
    title.value = '修改地址'
  } catch (error) {
    console.error('获取地址详情失败:', error)
  }
}

// 处理删除地址
const handleDelete = async (address) => {
  try {
    await ElMessageBox.confirm('确认要删除该地址吗？')
    await delAddress(address.id)
    ElMessage.success('删除功')
    getList()
  } catch (error) {
    console.error('删除地址失败:', error)
  }
}

// 处理设置默认地址
const handleSetDefault = async (address) => {
  try {
    await setDefaultAddress(address.id)
    ElMessage.success('设置成功')
    getList()
  } catch (error) {
    console.error('设置默认地址失败:', error)
  }
}

// 处理地区选择变化
const handleRegionChange = (value) => {
  if (value && value.length === 3) {
    const [provinceId, cityId, districtId] = value;
    const province = regionOptions.value.find(p => p.value === provinceId);
    const city = province.children.find(c => c.value === cityId);
    const district = city.children.find(d => d.value === districtId);
    
    form.value.provinceId = provinceId;
    form.value.cityId = cityId;
    form.value.districtId = districtId;
    form.value.province = province.label;
    form.value.city = city.label;
    form.value.district = district.label;
  }
}

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    provinceId: undefined,
    cityId: undefined,
    districtId: undefined,
    detailAddress: '',
    isDefault: 0
  }
  regionIds.value = []
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单提交
const submitForm = async () => {
  if (!addressRef.value) return
  
  try {
    await addressRef.value.validate()
    
    if (form.value.id) {
      await updateAddress(form.value)
      ElMessage.success('修改成功')
    } else {
      await addAddress(form.value)
      ElMessage.success('添加成功')
    }
    
    open.value = false
    getList()
  } catch (error) {
    console.error('保存地址失败:', error)
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.address-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  &.is-default {
    border: 2px solid var(--el-color-primary);
  }

  .address-info {
    h3 {
      margin: 0 0 10px;
      font-size: 16px;
      color: #333;
    }

    p {
      margin: 5px 0;
      color: #666;
      font-size: 14px;
    }

    .el-tag {
      margin-top: 10px;
    }
  }

  .address-actions {
    border-top: 1px solid #eee;
    padding-top: 10px;
    text-align: right;

    .el-button {
      margin-left: 10px;
    }
  }

  &.add-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
    border: 1px dashed #dcdfe6;
    background-color: #fff;

    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }

    .el-icon {
      font-size: 30px;
      margin-bottom: 10px;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  min-height: 80px;
}
</style> 